package command

import (
	"flag"
	"fmt"
	"go-LineScriptCommand/container"
	"strings"
)

type DocShowCmd struct {
	doc      string //接收输入变量
	priority int    //优先级
}

func init() {
	RegisterCommand(&DocShowCmd{
		priority: 1,
	})
}

// 绑定
func (m *DocShowCmd) Bind() {
	flag.StringVar(&m.doc, m.GetName(), "", m.GetDesc())
}

// 满足条件才执行命令
func (m *DocShowCmd) Condition() bool {
	return m.doc != ""
}

// 执行命令
func (m *DocShowCmd) Execute() {
	//m.doc长度不能小于2
	if len(m.doc) < 2 {
		fmt.Println("函数名长度不能小于2")
		return
	}
	names := container.GetAllFunName()
	var vague []string
	//精准匹配+模糊记录
	for _, name := range names {
		if name == m.doc {
			doc := container.ExecuteFun(m.doc, "-doc")
			fmt.Println(doc)
			return
		}
		if strings.Contains(name, m.doc) {
			vague = append(vague, name)
		}
	}
	if len(vague) == 0 {
		fmt.Println("未找到函数")
		return
	}
	if len(vague) == 1 {
		doc := container.ExecuteFun(vague[0], "-doc")
		fmt.Println(doc)
		return
	}
	fmt.Println("找到多个函数:")
	var fundesc []string
	for _, fun := range vague {
		docs := container.ExecuteFun(fun, "-doc")
		if docs != "" {
			//截取第1行有内容的
			docSp := strings.Split(docs, "\n")
			doc := ""
			for _, v1 := range docSp {
				//去除空格
				v1 = strings.TrimSpace(v1)
				if v1 != "" {
					doc = v1
					//去掉开头的功能:
					doc = strings.Replace(doc, "功能:", "", 1)
					doc = strings.TrimSpace(doc)
					break
				}
			}
			fundesc = append(fundesc, fun+"->"+doc)
		}

	}
	//打印
	for _, v := range fundesc {
		fmt.Println(v)
	}
}

// 获取命令名称
func (m *DocShowCmd) GetName() string {
	return "doc"
}

// 获取命令描述
func (m *DocShowCmd) GetDesc() string {
	return "打印函数使用文档(支持模糊) 例如: -doc if, 精准匹配是详情,模糊匹配是相关函数列表"
}

// 优先级  ,0最低...
func (m *DocShowCmd) GetPriority() int {
	return m.priority
}

// 是否终止
func (m *DocShowCmd) IsExit() bool {
	return true
}
